<?php

namespace web\models\account;

use peng\helpers\ArrayHelper;
use peng\helpers\Config;
use peng\helpers\StringHelper;

/**
 * 模型-注册
 *
 * @author Administrator
 */
class SignupModel extends \common\base\BaseModel {

    /**
     * 主键id
     * 
     * @var int 
     */
    public $aid;

    /**
     * 注册账号类型[0=司机、1=企业、2=团体]
     * 
     * @var string 
     */
    public $rtype;

    /**
     * 账号类型[0=手机号、1=email]
     * 
     * @var string 
     */
    public $utype;

    /**
     * 邮件地址或手机
     * 
     * @var string 
     */
    public $loginname;

    /**
     * 密码
     * 
     * @var string 
     */
    public $password;

    /**
     * 确认密码
     * 
     * @var string 
     */
    public $cfmpwd;

    /**
     * 验证码
     * 
     * @var string 
     */
    public $verifycode;

    /**
     * 规则
     * 
     * @return array
     */
    public function rules() {
        return array(
            array('rtype', 'in', 'range' => array(0, 1, 2)),
            array('utype', 'in', 'range' => array(0, 1)),
            array(array('loginname', 'verifycode'), 'required'),
            array('password', 'string', 'min' => 6, 'max' => 16),
            array('loginname', 'string', 'length' => 11, 'onWhen' => function ($model) {
            return 0 == $model->utype; // 手机号
        }),
            array('loginname', 'number', 'onWhen' => function ($model) {
            return 0 == $model->utype; // 手机号
        }),
            array('loginname', 'email', 'onWhen' => function ($model) {
            return 1 == $model->utype; // EMIAL
        }),
            array('cfmpwd', 'compare', 'compareAttribute' => 'password', 'message' => '密码与确认密码不一致。')
        );
    }

    /**
     * 属性名称
     * 
     * @return array
     */
    public function attrLabels() {
        return array(
            'rtype' => '注册用户类型',
            'utype' => '注册账号类型',
            'loginname' => '账号',
            'password' => '密码',
            'cfmpwd' => '确认密码',
            'verifycode' => '验证码',
        );
    }

    /**
     * 执行数据验证
     * 
     * @param bool $clearErrors [验证前清除错误]
     * @return bool
     */
    public function validate($clearErrors = TRUE) {
        if (!parent::validate($clearErrors)) {
            return FALSE;
        } elseif (0 == $this->utype && !StringHelper::checkMobileValid($this->loginname)) {
            return $this->appendError('loginname', '手机号不正确。');  // 验证手机号
        }

        // 验证注册码
        $config = Config::get('cookie', 'account');
        $cookieName = ArrayHelper::get($config, 'reg_code_name');
        $encryptKey = ArrayHelper::get($config, 'encryption_key');

        $vcode = \Peng::$app->request->cookie($cookieName);
        if (!isset($vcode[0]) || $vcode !== md5(strtolower($this->verifycode) . $encryptKey)) {
            return $this->appendError('verifycode', '验证码错误。');
        }

        return TRUE;
    }

}
